<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-row style="margin-bottom: 20px">
        <el-form-item label="订单号" prop="combineOrder" style="margin-bottom: 100px">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-row>
      <el-row style="margin-bottom: 20px">
        <el-form-item label="订单状态" prop="orderState" >
          <el-radio-group type="button" v-model="queryParams.orderState" @change="handleChange">
            <el-radio-button  label="">全部</el-radio-button>
            <el-radio-button label="wait_pay">待付款</el-radio-button>
            <el-radio-button label="wait_ship">待发货</el-radio-button>
            <el-radio-button label="shipped">待收货</el-radio-button>
            <el-radio-button label="received">已收货</el-radio-button>
            <!--              <el-radio-button label="refund_apply">退款中</el-radio-button>-->
            <!--              <el-radio-button label="refund_success">已退款</el-radio-button>-->
<!--            <el-radio-button label="await_evaluate">待评价</el-radio-button>-->
            <el-radio-button label="finished">已完成</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row style="margin-bottom: 50px">
        <el-form-item label="下单时间" prop="">
          <el-date-picker
            v-model="daterangeCreateTime"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      </el-row>
      <el-form-item>
        <el-button type="primary"   size="mini" @click="handleQuery">搜索</el-button>
        <el-button  size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['shopping:mallOrder:export']"
          v-if="false"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :height="tableHeight"
              :data="mallOrderList"
              :span-method="objectSpanMethod"
              border
              style="width: 100%; margin-top: 20px">
      <el-table-column label="订单号" align="center" prop="mallOrderMeshOrderId" />
      <el-table-column label="商品信息" align="center" prop="productInfo" show-overflow-tooltip width="450"/>
      <el-table-column label="商品状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <dict-tag :options="viewState" :value="scope.row.orderState"/>
        </template>
      </el-table-column>
      <el-table-column label="实际支付金额" align="center" prop="payPrice" />

      <el-table-column label="订单状态" align="center" prop="meshState">
        <template slot-scope="scope">
          <dict-tag :options="orderStateOptions" :value="scope.row.meshState"/>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="date" />
      <!--      <el-table-column label="配送方式" align="center" prop="distributionDmode">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="distributionDmodeOptions" :value="scope.row.distributionDmode"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.meshState == 'wait_ship'"
            @click="changeDelivery(scope.row)"
          >发送货</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
                <span class="el-dropdown-link">
                 更多<i class="el-icon-d-arrow-right el-icon--right"></i>
                </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="changeOrderDetails"  >订单详情</el-dropdown-item>
              <el-dropdown-item command="changeOrderRemark" >订单备注</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--点击订单详情弹出的对应的商品订单信息-->
    <el-dialog :close-on-click-modal="false" :title="titleDetails" :visible.sync="openDetails" width="700px" append-to-body>

      <el-form :model="addrInfo"  label-width="100px" >
        <div class="contentView">
          <el-form-item label="收货信息" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="收货人：" >
              {{addrInfo.name}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货电话：" >
              {{addrInfo.phone}}
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="收货地址：" >
                {{addrInfo.address}}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

        <el-form label-width="100px" >
          <div class="contentView">
          <el-form-item label="商品信息" />
              <div class="levelOne" v-for="(item, index) in orderList" :key="index">
                <div class="lineVine" v-for="value in item">
                      <el-image class="proImg" :src="value.productImage"/>
                      <div class="floatLeftView rightContentText">
                        {{value.productName}} | {{value.specificationName}} {{value.totalPrice}} × {{value.num}}
                      </div>
                      <div class="floatLeftView rightBtn">
                        {{value.orderState}}
                      </div>
                  <div class="cleanView"></div>
                </div>
                <div class="lineVine" v-if="item[0].mode == 'N'">
                  <div class="floatLeftView blockView"> 快递方式：{{item[0].courierCompany}}</div>
                  <div class="floatLeftView blockView"> 快递单号：{{item[0].courierNumber}}</div>
                  <div class="floatLeftView blockView">发货时间：{{item[0].courierTime}}</div>
                </div>

                <div class="cleanView"></div>
              </div>
          </div>
        </el-form>





      <div class="contentView">
        <el-form :model="mesh"  label-width="100px" >
          <el-form-item label="订单信息" />
          <div class="none_border">
            <el-row>
              <el-col :span="12">
                <el-form-item label="订单号：" >
                  {{mesh.orderId}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单状态：" >
                  {{mesh.orderState}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品总价：" >
                  {{mesh.totalPrice}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优惠券金额：" >
                  {{mesh.deductionPrice}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="实际支付：" >
                  {{mesh.payPrice}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下单时间：" >
                  {{mesh.createTime}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="支付方式：" >
                  微信支付
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付时间：" >
                  {{mesh.payTime}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="买家备注：" >
                  {{mesh.buyerComment}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="商家备注：" >
                  {{mesh.saleComment}}
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetailsCancel">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="titleDelivery" :visible.sync="openDelivery" width="800px" append-to-body>
      <el-table  ref="multipleTable" v-loading="loading"  :data="productList" @selection-change="handleSelectionProductOrder" >
        <el-table-column type="selection" width="55" align="center"   />
        <el-table-column label="商品图片" width="150" align="center" prop="productImage">-->
          <template width="120" slot-scope="scope">
            <img style="width:60px;height:60px;border:none;" :src="scope.row.productImage">
          </template>
        </el-table-column>
        <el-table-column label="商品信息" align="left" prop="mergeInformation"  />
      </el-table>
      <el-divider></el-divider>

      <el-form ref="getMallOrderValue" :model="getMallOrderValue" :rules="rules" label-width="80px">
        <el-row style="margin-bottom: 10px">
        <el-form-item label="发货类型">
          <el-radio-group v-model="getMallOrderValue.deliveryType">
            <el-radio
              v-for="dict in deliverytypeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        </el-row>
        <el-row style="margin-bottom: 10px">
        <el-form-item label="快递公司" prop="courierCompany" v-if="this.getMallOrderValue.deliveryType=='deliver_goods'">
          <el-select v-model="getMallOrderValue.courierCompany" placeholder="请选择快递公司">
            <el-option
              v-for="dict in courierCompanyOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        </el-row>

        <el-row style="margin-bottom: 10px">
        <el-form-item label="快递单号" prop="courierNumber" v-if="this.getMallOrderValue.deliveryType=='deliver_goods'">
          <el-input v-model="getMallOrderValue.courierNumber" placeholder="请输入快递单号" />
        </el-form-item>
        </el-row>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDelivery">确认</el-button>
        <el-button @click="openDeliveryCancel">取消</el-button>
      </div>
    </el-dialog>

    <!--//详细订单查看-->
    <el-dialog :close-on-click-modal="false" :title="titlePlatformRemark " :visible.sync="openPlatformRemark" width="700px" append-to-body>
      <el-form ref="RemarkValue" :model="RemarkValue" :rules="rules" label-width="80px">
        <el-form-item label="平台备注" prop="platformRemark">
          <el-input v-model="RemarkValue.platformRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="subPlatformRemark">确认</el-button>
        <el-button @click="openPlatformRemarkCancel">取消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {editStatus,getOrderMeshId,listMallOrder, getMallOrder,queryOrderDetail} from "@/api/shopping/mallOrder";
  import {getMallOrderMesh,listMallOrderMesh,updateOrderMesh} from "@/api/shopping/mallOrderMesh";
  export default {
    name: "MallOrder",
    data() {
      return {
        newArr:[],
        //批量选中订单商品进行发送货
        mallOrderIds:[],
        productList:[],
        //点击订单详情后弹出的商品订单信息
        orderDetailsList:[],
        // 创建时间时间范围
        daterangeCreateTime: [],
        color:'#FFDAB9',
        //点击发送货选中的id
        tempId :"",
        //下单人信息
        userInfo:{},
        // 发货类型字典
        deliverytypeOptions: [],
        viewState: [],
        //合并订单信息
        mallOrderValue:{
          orderId:null,
          name:null,
          gainIntegral:null,
          useIntegral :null,
          payState:null,
          payOrderNo :null,
          payTime :null,
          payType:null,
        },
        tableHeight:0,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        //商城订单总条数
        total1:0,
        // 总条数
        total: 0,
        // 商城订单表格数据
        mallOrderList: [
        ],
        //查看详情订单标题
        titleLook:"",
        // 弹出层标题
        //查看详情信息弹出层
        openLook:false,
        title: "",
        //订单详情弹窗标题
        titleDetails:"",
        //发送货弹出标题
        titleDelivery:"",
        //平台备注标题
        titlePlatformRemark:"",
        // 是否显示弹出层
        open: false,
        //点击订单详情弹出的对应的订单详情弹出层
        openDetails:false,
        //发送货详情弹出层
        openDelivery:false,
        //平台备注弹出层
        openPlatformRemark:false,
        // 快递公司字典
        courierCompanyOptions: [],
        // 订单状态字典
        orderStateOptions: [],
        // 退款状态字典
        refundStatusOptions: [],
        // 退款支付状态字典
        refundPayStatusOptions: [],
        // 退款原因字典
        refundReasonOptions: [],
        // 配送方式字典
        distributionDmodeOptions: [],
        // 是否已评价字典
        commentStatusOptions: [],
        //商城订单查询参数
        query:{
          pageNum: 1,
          pageSize: 10,
          mergeOrderId:null,
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderId: null,
          name: null,
          memberId: null,
          gainIntegral: null,
          useIntegral: null,
          payState: null,
          payPrice: null,
          payOrderNo: null,
          payTime: null,
          payType: null,
          commentState: null,
          shipState: null,
          aftersaleState: null,
          platformRemark: null,
          customerRemark: null,
          orderState: null,
        },
        // 表单参数
        form: {},
        //商城订单详情数据
        mallOrderForm:{},
        //选中发货中发货类型，快递公司，快递单号
        getMallOrderValue:{},
        RemarkValue:{},
        // 表单校验
        rules: {

          deliveryType:[
            { required: true, message: '请选择发货类型', trigger: 'blur' }
          ],
          courierCompany:[
            { required: true, message: '请选择快递公司', trigger: 'blur' }
          ],
          courierNumber:[
            { required: true, message: '请输入快递单号', trigger: 'blur' }
          ],
        },
        mesh:{},
        addrInfo:{},
        orderList:[]
      };
    },
    created() {
      this.getList();
      this.calHeight()
      this.getDicts("delivery_type").then(response => {
        this.deliverytypeOptions = response.data;
      });
      this.getDicts("order_state").then(response => {
        this.orderStateOptions = response.data;
      });
      this.getDicts("sys_refund_status").then(response => {
        this.refundStatusOptions = response.data;
      });
      this.getDicts("logistics_company").then(response => {
        this.courierCompanyOptions = response.data;
      });
      this.getDicts("sys_yes_no").then(response => {
        this.refundPayStatusOptions = response.data;
        this.commentStatusOptions = response.data;

      });
      this.getDicts("refund_cause").then(response => {
        this.refundReasonOptions = response.data;
      });
      this.getDicts("sys_distribution_dmode").then(response => {
        this.distributionDmodeOptions = response.data;
      });
      this.getDicts("view").then(response => {
        this.viewState = response.data;
      });
    },
    beforeRouteEnter(to, form, next) {
      next(vm => {
        const orderState = vm.$route.query && vm.$route.query.orderState;
        if(orderState){
          vm.queryParams.orderState = orderState;
          vm.getList();
        }
      });
    },
    watch: {
      'showSearch':'calHeight'
    },

    methods: {
      //合并单元格
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6) {
          if (row.nums&&row.nums>0) {
            return {
              rowspan: row.nums,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      },

      //详情表格中的查看信息
      handeLook(row){
        const id = row.id
        getMallOrder(id).then(response => {
          this.mallOrderForm = response.data;
        });
        let ids = row.mergeOrderId
        getMallOrderMesh(ids).then(response=>{
          this.form= response.data;
        })
        this.titleLook="查看详细订单";
        this.openLook = true;
      },

      //发送货提交
      submitDelivery(){
        this.openDelivery=true;
        this.titleDelivery = "发送货";
        if (this.mallOrderIds==null){
          this.msgError("没有商品信息!")
          return
        }
        let query={
          ids:this.mallOrderIds.join(","),
          deliveryType :this.getMallOrderValue.deliveryType,
          courierCompany:this.getMallOrderValue.courierCompany,
          courierNumber:this.getMallOrderValue.courierNumber,
        }
        this.$refs["getMallOrderValue"].validate(valid => {
          if (valid) {
            editStatus(query).then(response => {
              debugger
              this.msgSuccess("发货成功")
              this.openDelivery=false;
              this.reset();
              this.getList();
            })

          }
        });
      },
      //发送货按钮
      changeDelivery(row){
        let that = this
        this.reset();
        let query= {
          id :row.id
        }
        getOrderMeshId(query).then(response => {
          this.productList = response.rows;
          this.openDelivery=true;
          this.titleDelivery = "发送货";
          console.log(this.$refs)
          this.$nextTick(()=>{
            that.$refs.multipleTable.toggleAllSelection();
          })

        });

      },
      //查询订单状态
      handleChange(val){
        this.queryParams.orderState = val;
        this.getList();
      },
      //更多操作
      handleCommand(command, row){
        switch (command) {
          case "changeOrderDetails":
            this.changeOrderDetails(row);
            break;
          case "changeOrderRemark":
            this.changeOrderRemark(row);
            break;
          case "changeDelivery":
            this.changeDelivery(row);
            break;
          default:
            break;
        }
      },
      groupBy(array, f){
          let groups = {};
          array.forEach(function (o) {
            var group = JSON.stringify(f(o));
            groups[group] = groups[group] || [];
            groups[group].push(o);
          });
          return Object.keys(groups).map(function (group) {
            return groups[group];
          });

      },
      sort(list,span){
        let sorted = this.groupBy(list, function (item) {
          return [item[span]];
        });
        return sorted
      },
      //订单详情
      changeOrderDetails(row){
        this.openDetails = true;
        this.titleDetails = "订单详情";
        this.query.mergeOrderId=row.id
        queryOrderDetail(row.id).then(res=>{
          this.mesh = res.data.mesh
          this.addrInfo = res.data.addr
          this.orderList = this.sort(res.data.order,"courierNumber")
        })
        // listMallOrder(this.query).then(response => {
        //   this.orderDetailsList = response.rows;
        // });
      },
      //订单备注
      changeOrderRemark(row){
        this.reset();
        const id = row.id
        getMallOrderMesh(id).then(response => {
          this.RemarkValue = response.data;
          this.openPlatformRemark = true;
          this.titlePlatformRemark = "平台备注"
        });
        this.tempId = row.id
      },
      // 合并订单的平台备注
      subPlatformRemark(){
        let query={
          id: this.tempId,
          remark: this.RemarkValue.platformRemark
        }
        updateOrderMesh(query).then(response => {
          this.msgSuccess("备注成功")
          this.openPlatformRemark = false;
          this.reset();
          this.getList();
        });
      },
      calHeight () {
        this.$nextTick(() => {
          const rect = this.$refs.appcontainer.getBoundingClientRect();
          let height= this.$refs.queryForm.$el.offsetHeight;
          this.tableHeight = rect.height-height-120;
        })
      },
      /** 查询商城订单列表 */
      getList() {
        this.loading = true;
        //根据时间查询
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        listMallOrderMesh(this.queryParams).then(response => {
          this.mallOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      openDetailsCancel(){
        this.openDetails = false;
        this.reset();
      },
      openDeliveryCancel(){
        this.openDelivery = false;
        this.reset();
      },
      openPlatformRemarkCancel(){
        this.openPlatformRemark = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.RemarkValue = {
          id:null,
          platformRemark:null
        }
        this.getMallOrderValue ={
          deliveryType:'deliver_goods',
          courierCompany :null,
          courierNumber:null,
        };
        this.form = {
          id: null,
          orderId: null,
          name: null,
          memberId: null,
          gainIntegral: null,
          useIntegral: null,
          payState: null,
          payPrice: null,
          payOrderNo: null,
          payTime: null,
          payType: null,
          delState: null,
          commentState: null,
          delUser: null,
          shipState: null,
          delType: null,
          aftersaleState: null,
          delTime: null,
          platformRemark: null,
          createBy: null,
          customerRemark: null,
          createType: null,
          createTime: null,
          orderState: null,
          updateBy: null,
          updateType: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.showSearch=false;
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.daterangeCreateTime=null;
        this.handleQuery();
      },
      // 发送货多选框选中数据
      handleSelectionProductOrder(selection){
        this.mallOrderIds = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.$refs.multipleTable.toggleRowSelection(this.newArr);
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商城订单";
      },


      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商城订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMallOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
      }
    }
  };
</script>
<style scoped>
  .el-form-item {
    margin-bottom: 0px !important;
  }
  .el-divider{
    margin: 6px 0 !important;
  }
  .contentView{
    width: 96%;
    /*padding: 0 20px 0 0;*/
    margin-bottom: 20px;
    margin-left: 18px;
    border: 1px solid #dcdfe6;
    border-radius: 10px;
  }
  .levelOne{
    padding: 4px 10px;
    box-sizing: border-box;
  }
  .levelOne .proImg{
    height: 50px;
    width: 50px;
    float: left;
    border-radius: 4px;
  }
  .levelOne .floatLeftView{
    float: left;
  }
  .levelOne .rightContentText{
    width: 480px;
    line-height: 25px;
    padding: 0 10px;
    box-sizing: border-box;
  }
  .levelOne .lineVine{
    padding: 2px 0;
  }
  .rightBtn{
    height: 26px;
    line-height: 26px;
    border: 1px solid #ccc;
    padding: 0 5px;
    box-sizing: border-box;
    font-size: 12px;
    border-radius: 4px;
    margin-top: 10px;
  }
  .cleanView{
    clear: both;
  }
  .levelOne .blockView{
    line-height: 35px;
    font-size: 14px;
    padding: 0 5px;
    margin-right: 10px;
  }
</style>
